package com.code2roc.jarmanage.util;

import com.code2roc.jarmanage.Application;
import com.code2roc.jarmanage.depoly.DepolyPlatform;
import com.code2roc.jarmanage.depoly.DepolyServiceFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ResourceUtil {

    public static void initResource() throws Exception {
        URL sourcePathURL = Application.class.getResource("/resources");
        if (sourcePathURL != null) {
            File file = new File("resources");
            if (file.exists()) {
                file.delete();
            }
            String url = sourcePathURL.getPath();
            File resource = new File(url);
            String s = "";
            if (EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows)) {
                s = resource.getParent().replaceAll("(!|file:\\\\)", "");
            } else {
                s = resource.getParent().replaceAll("file:", "").replace("!", "");
            }
            copyResourcesToDirectory(new JarFile(new File(URLDecoder.decode(s, "utf-8"))), "resources", "resources");
        }

        sourcePathURL = Application.class.getResource("/webapp");
        if (sourcePathURL != null) {
            File file = new File("webapp");
            if (file.exists()) {
                file.delete();
            }
            String url = sourcePathURL.getPath();
            File resource = new File(url);
            String s = "";
            if (EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows)) {
                s = resource.getParent().replaceAll("(!|file:\\\\)", "");
            } else {
                s = resource.getParent().replaceAll("file:", "").replace("!", "");
            }
            copyResourcesToDirectory(new JarFile(new File(URLDecoder.decode(s, "utf-8"))), "webapp", "webapp");
        }

        File deplyDir = new File("depoly");
        String depolyPath = new File(deplyDir.getAbsolutePath()).getParentFile().getAbsolutePath();
        String templatePath =  "resources" + File.separator + "template" + File.separator + "tinyfilemanager.php";
        String fileManagePath = "webapp" + File.separator + "pages" + File.separator + "plugin" + File.separator + "filemanage.php";
        FileUtil.copyFile(templatePath,fileManagePath);
        String fileContent = FileUtil.readFileContentKeepLine(fileManagePath);
        fileContent = fileContent.replace("$_SERVER['DOCUMENT_ROOT']", "'" + depolyPath + "'");
        if(EnviromentUtil.getDepolyPlaform()==DepolyPlatform.Windows){
            fileContent = fileContent.replace("$_SERVER['HTTP_HOST_PATH']", "$_SERVER['HTTP_HOST'].'/pages/plugin/filemanage.php'");
        }else{
            fileContent = fileContent.replace("$_SERVER['HTTP_HOST_PATH']", "$_SERVER['HTTP_HOST']");
        }
        fileContent = fileContent.replace("$_SERVER['EXCLUDE_ITEMS']", "array('webapp')");
        FileUtil.writeFile(fileManagePath, fileContent, false);

        File file = new File("webapp/static");
        if(!file.exists()){
            file.mkdirs();
        }
        depolyPath = file.getAbsolutePath();
        fileManagePath = "webapp" + File.separator + "pages" + File.separator + "plugin" + File.separator + "staticdepoly.php";
        FileUtil.copyFile(templatePath,fileManagePath);
        fileContent = FileUtil.readFileContentKeepLine(fileManagePath);
        fileContent = fileContent.replace("$_SERVER['DOCUMENT_ROOT']", "'" + depolyPath + "'");
        if(EnviromentUtil.getDepolyPlaform()==DepolyPlatform.Windows){
            fileContent = fileContent.replace("$_SERVER['HTTP_HOST_PATH']", "$_SERVER['HTTP_HOST'].'/pages/plugin/staticdepoly.php'");
        }else{
            fileContent = fileContent.replace("$_SERVER['HTTP_HOST_PATH']", "$_SERVER['HTTP_HOST']");
        }
        fileContent = fileContent.replace("$_SERVER['EXCLUDE_ITEMS']", "array()");
        FileUtil.writeFile(fileManagePath, fileContent, false);
        fileContent = null;
    }

    public static void copyResourcesToDirectory(JarFile fromJar, String jarDir, String destDir) throws IOException {
        for (Enumeration<JarEntry> entries = fromJar.entries(); entries.hasMoreElements(); ) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(jarDir + "/") && !entry.isDirectory()) {
                File dest = new File(destDir + File.separator + entry.getName().substring(jarDir.length() + 1));
                File parent = dest.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                FileOutputStream out = new FileOutputStream(dest);
                InputStream in = fromJar.getInputStream(entry);
                try {
                    byte[] buffer = new byte[8 * 1024];

                    int s = 0;
                    while ((s = in.read(buffer)) > 0) {
                        out.write(buffer, 0, s);
                    }
                } catch (IOException e) {

                } finally {
                    try {
                        in.close();
                    } catch (IOException ignored) {
                    }
                    try {
                        out.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    }
}
